package com.example.pgtest.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.pgtest.entity.NodeInfo;
import com.example.pgtest.entity.User;
import com.example.pgtest.mapper.UserMapper;
import com.example.pgtest.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WDK
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 1.获取事务控制管理器
    // @Autowired
    private DataSourceTransactionManager transactionManager;

    @Autowired
    private StoredProcedureUtil storedProcedureUtil;

    public Object selectInfo1(String method) {

        // 2.获取事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        // 3.设置事务隔离级别，开启新事务
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        // 4.获得事务状态
        TransactionStatus status = transactionManager.getTransaction(def);

        Object data;
        try {
            // 5.具体的数据库操作（多个）
            String info = baseMapper.getInfo(method);
            String[] split = info.split(",");
            data = baseMapper.getData(split[1].substring(0,split[1].length()-1));
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw new RuntimeException(e.getMessage());
        }
        return data;
    }

    @Transactional
    public Object selectInfo2(String method) {
        List<Object> data = new ArrayList<>();
        try {
            // 5.具体的数据库操作（多个）
            String info = baseMapper.getInfo(method);
            String[] split = info.split(",");
            String substring = split[1].substring(0, split[1].length() - 1);
            List<NodeInfo> data1 = baseMapper.getData(substring);
            log.info("获取数据为：【{}】", JSON.toJSONString(data1));
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return data;
    }
    @Override
    public List<NodeInfo> selectInfo(String method) {
        return storedProcedureUtil.executeStoredProcedure(NodeInfo.class, method);
    }
}
